"""
模拟数据库模块

使用内存字典模拟数据库操作，包括：
- 用户 CRUD 操作
- 用户查询功能
"""

from typing import Optional, List, Dict
from datetime import datetime

from .models import UserInDB, UserRegister, UserUpdate
from .utils import hash_password, generate_id, get_current_timestamp


# ========== 内存数据库 ==========

# 模拟用户数据库（实际项目中应使用 PostgreSQL、MySQL 等）
USERS_DB: Dict[int, UserInDB] = {}

# 初始化计数器
_user_id_counter = 0


def _get_next_id() -> int:
    """获取下一个用户 ID"""
    global _user_id_counter
    _user_id_counter += 1
    return _user_id_counter


# ========== 初始化测试数据 ==========


def init_test_data():
    """初始化测试数据"""
    test_users = [
        {
            "username": "admin",
            "email": "admin@example.com",
            "password": "Admin123",
            "full_name": "系统管理员",
            "age": 30,
            "role": "admin",
        },
        {
            "username": "john",
            "email": "john@example.com",
            "password": "User123",
            "full_name": "John Doe",
            "age": 25,
            "role": "user",
        },
        {
            "username": "jane",
            "email": "jane@example.com",
            "password": "User123",
            "full_name": "Jane Smith",
            "age": 28,
            "role": "user",
        },
    ]

    for user_data in test_users:
        user_id = _get_next_id()
        now = get_current_timestamp()
        
        user = UserInDB(
            id=user_id,
            username=user_data["username"],
            email=user_data["email"],
            hashed_password=hash_password(user_data["password"]),
            full_name=user_data["full_name"],
            age=user_data["age"],
            role=user_data["role"],
            is_active=True,
            created_at=now,
            updated_at=now,
        )
        USERS_DB[user_id] = user


# 初始化测试数据
init_test_data()


# ========== 查询操作 ==========


def get_user_by_username(username: str) -> Optional[UserInDB]:
    """
    根据用户名查询用户
    
    Args:
        username: 用户名
        
    Returns:
        用户对象，不存在则返回 None
    """
    for user in USERS_DB.values():
        if user.username == username:
            return user
    return None


def get_user_by_email(email: str) -> Optional[UserInDB]:
    """
    根据邮箱查询用户
    
    Args:
        email: 邮箱地址
        
    Returns:
        用户对象，不存在则返回 None
    """
    for user in USERS_DB.values():
        if user.email == email:
            return user
    return None


def get_user_by_id(user_id: int) -> Optional[UserInDB]:
    """
    根据 ID 查询用户
    
    Args:
        user_id: 用户 ID
        
    Returns:
        用户对象，不存在则返回 None
    """
    return USERS_DB.get(user_id)


def get_all_users(
    skip: int = 0,
    limit: int = 10,
    search: Optional[str] = None,
    role: Optional[str] = None,
    is_active: Optional[bool] = None,
) -> List[UserInDB]:
    """
    获取用户列表（支持分页、搜索、筛选）
    
    Args:
        skip: 跳过的记录数
        limit: 返回的最大记录数
        search: 搜索关键词（匹配用户名或邮箱）
        role: 角色筛选
        is_active: 活跃状态筛选
        
    Returns:
        用户列表
    """
    users = list(USERS_DB.values())
    
    # 应用筛选条件
    if search:
        search_lower = search.lower()
        users = [
            u for u in users
            if search_lower in u.username.lower() or search_lower in u.email.lower()
        ]
    
    if role:
        users = [u for u in users if u.role == role]
    
    if is_active is not None:
        users = [u for u in users if u.is_active == is_active]
    
    # 应用分页
    return users[skip : skip + limit]


def count_users(
    search: Optional[str] = None,
    role: Optional[str] = None,
    is_active: Optional[bool] = None,
) -> int:
    """
    统计用户数量
    
    Args:
        search: 搜索关键词
        role: 角色筛选
        is_active: 活跃状态筛选
        
    Returns:
        用户数量
    """
    users = list(USERS_DB.values())
    
    if search:
        search_lower = search.lower()
        users = [
            u for u in users
            if search_lower in u.username.lower() or search_lower in u.email.lower()
        ]
    
    if role:
        users = [u for u in users if u.role == role]
    
    if is_active is not None:
        users = [u for u in users if u.is_active == is_active]
    
    return len(users)


# ========== 创建操作 ==========


def create_user(user_data: UserRegister) -> UserInDB:
    """
    创建新用户
    
    Args:
        user_data: 用户注册数据
        
    Returns:
        创建的用户对象
    """
    user_id = _get_next_id()
    now = get_current_timestamp()
    
    user = UserInDB(
        id=user_id,
        username=user_data.username,
        email=user_data.email,
        hashed_password=hash_password(user_data.password),
        full_name=user_data.full_name,
        age=user_data.age,
        role="user",  # 默认为普通用户
        is_active=True,
        created_at=now,
        updated_at=now,
    )
    
    USERS_DB[user_id] = user
    return user


# ========== 更新操作 ==========


def update_user(user_id: int, user_data: UserUpdate) -> Optional[UserInDB]:
    """
    更新用户信息
    
    Args:
        user_id: 用户 ID
        user_data: 更新数据
        
    Returns:
        更新后的用户对象，用户不存在则返回 None
    """
    user = USERS_DB.get(user_id)
    if not user:
        return None
    
    # 更新字段
    update_dict = user_data.model_dump(exclude_unset=True)
    for field, value in update_dict.items():
        setattr(user, field, value)
    
    user.updated_at = get_current_timestamp()
    
    return user


def update_user_role(user_id: int, role: str) -> Optional[UserInDB]:
    """
    更新用户角色
    
    Args:
        user_id: 用户 ID
        role: 新角色
        
    Returns:
        更新后的用户对象，用户不存在则返回 None
    """
    user = USERS_DB.get(user_id)
    if not user:
        return None
    
    user.role = role
    user.updated_at = get_current_timestamp()
    
    return user


def deactivate_user(user_id: int) -> Optional[UserInDB]:
    """
    停用用户（软删除）
    
    Args:
        user_id: 用户 ID
        
    Returns:
        更新后的用户对象，用户不存在则返回 None
    """
    user = USERS_DB.get(user_id)
    if not user:
        return None
    
    user.is_active = False
    user.updated_at = get_current_timestamp()
    
    return user


# ========== 删除操作 ==========


def delete_user(user_id: int) -> bool:
    """
    删除用户（硬删除）
    
    Args:
        user_id: 用户 ID
        
    Returns:
        是否删除成功
    """
    if user_id in USERS_DB:
        del USERS_DB[user_id]
        return True
    return False


# ========== 统计操作 ==========


def get_user_stats() -> Dict[str, int]:
    """
    获取用户统计信息
    
    Returns:
        统计信息字典
    """
    users = list(USERS_DB.values())
    
    return {
        "total_users": len(users),
        "active_users": len([u for u in users if u.is_active]),
        "inactive_users": len([u for u in users if not u.is_active]),
        "admin_users": len([u for u in users if u.role == "admin"]),
        "regular_users": len([u for u in users if u.role == "user"]),
    }

